extends Control

# 引用
var player: Player
var data_manager: DataManager
var cultivation_system: CultivationSystem

# 当前选中的功法
var selected_technique = null
var current_technique = null

# 节点引用
@onready var technique_container = $MarginContainer/VBoxContainer/Content/TechniqueList/ScrollContainer/TechniqueContainer
@onready var current_name_label = $MarginContainer/VBoxContainer/Content/CurrentTechnique/Panel/VBoxContainer/NameLabel
@onready var current_level_label = $MarginContainer/VBoxContainer/Content/CurrentTechnique/Panel/VBoxContainer/LevelLabel
@onready var current_progress_bar = $MarginContainer/VBoxContainer/Content/CurrentTechnique/Panel/VBoxContainer/ProgressBar
@onready var current_description_label = $MarginContainer/VBoxContainer/Content/CurrentTechnique/Panel/VBoxContainer/DescriptionLabel
@onready var current_type_label = $MarginContainer/VBoxContainer/Content/CurrentTechnique/Panel/VBoxContainer/StatsContainer/TypeLabel
@onready var current_element_label = $MarginContainer/VBoxContainer/Content/CurrentTechnique/Panel/VBoxContainer/StatsContainer/ElementLabel
@onready var current_cultivation_speed_label = $MarginContainer/VBoxContainer/Content/CurrentTechnique/Panel/VBoxContainer/StatsContainer/CultivationSpeedLabel
@onready var current_spirit_recovery_label = $MarginContainer/VBoxContainer/Content/CurrentTechnique/Panel/VBoxContainer/StatsContainer/SpiritRecoveryLabel
@onready var current_breakthrough_label = $MarginContainer/VBoxContainer/Content/CurrentTechnique/Panel/VBoxContainer/StatsContainer/BreakthroughLabel
@onready var current_attack_label = $MarginContainer/VBoxContainer/Content/CurrentTechnique/Panel/VBoxContainer/BonusContainer/AttackLabel
@onready var current_defense_label = $MarginContainer/VBoxContainer/Content/CurrentTechnique/Panel/VBoxContainer/BonusContainer/DefenseLabel
@onready var current_speed_label = $MarginContainer/VBoxContainer/Content/CurrentTechnique/Panel/VBoxContainer/BonusContainer/SpeedLabel
@onready var spirit_stones_label = $MarginContainer/VBoxContainer/Content/CurrentTechnique/Panel/VBoxContainer/StatsContainer/SpiritStonesLabel
@onready var cultivate_button = $MarginContainer/VBoxContainer/Content/CurrentTechnique/Panel/VBoxContainer/CultivateButton
@onready var breakthrough_button = $MarginContainer/VBoxContainer/BottomButtons/BreakthroughButton

# 初始化节点
func _ready() -> void:
	# 等待节点树准备就绪
	await ready
	
	# 检查节点引用是否正确
	if not technique_container:
		push_error("技法容器节点未找到")
	
	# 检查当前功法显示节点
	if not current_name_label or not current_level_label or not current_progress_bar or not current_description_label:
		push_error("当前功法显示节点未找到")
	
	# 检查功法属性节点
	if not current_type_label or not current_element_label or not current_cultivation_speed_label or not current_spirit_recovery_label or not current_breakthrough_label:
		push_error("功法属性节点未找到")
	
	# 检查功法加成节点
	if not current_attack_label or not current_defense_label or not current_speed_label:
		push_error("功法加成节点未找到")
	
	# 连接按钮信号
	if cultivate_button:
		if not cultivate_button.pressed.is_connected(_on_cultivate_button_pressed):
			cultivate_button.pressed.connect(_on_cultivate_button_pressed)
	else:
		push_error("修炼按钮节点未找到")
	
	if breakthrough_button:
		if not breakthrough_button.pressed.is_connected(_on_breakthrough_button_pressed):
			breakthrough_button.pressed.connect(_on_breakthrough_button_pressed)
	else:
		push_error("突破按钮节点未找到")

# 初始化
func initialize(p_player: Player, p_data_manager: DataManager, p_cultivation_system: CultivationSystem) -> void:
	player = p_player
	data_manager = p_data_manager
	cultivation_system = p_cultivation_system
	
	# 更新界面
	update_ui()

# 显示界面
func show_ui() -> void:
	visible = true
	
	# 确保获取最新的玩家数据
	if player and player.cultivation_technique:
		current_technique = player.cultivation_technique
	
	# 刷新界面
	update_ui()

# 隐藏界面
func hide_ui() -> void:
	visible = false

# 更新界面
func update_ui() -> void:
	# 清空功法列表
	if technique_container:
		for child in technique_container.get_children():
			child.queue_free()
	
	# 获取玩家当前功法
	if player:
		current_technique = player.cultivation_technique
		# 更新灵石显示
		if spirit_stones_label:
			spirit_stones_label.text = "灵石: %d" % player.spirit_stones
	
	# 更新当前功法显示
	update_current_technique_display()
	
	# 填充可用功法列表
	populate_technique_list()
	
	# 更新突破按钮状态
	update_breakthrough_button()

# 更新当前功法显示
func update_current_technique_display() -> void:
	# 检查节点引用和当前功法
	if not current_name_label or not current_level_label or not current_progress_bar or not current_description_label:
		push_error("当前功法显示节点未找到")
		return
		
	if current_technique:
		current_name_label.text = current_technique.technique_name
		current_level_label.text = "等级: %d/%d" % [current_technique.level, current_technique.max_level]
		current_progress_bar.value = 50  # 这里应该根据实际修炼进度设置
		current_description_label.text = current_technique.description
		
		# 更新功法类型
		var type_text = "类型: "
		match current_technique.technique_type:
			CultivationTechnique.TechniqueType.FOUNDATION:
				type_text += "基础功法"
			CultivationTechnique.TechniqueType.ELEMENTAL:
				type_text += "元素功法"
			CultivationTechnique.TechniqueType.BODY:
				type_text += "炼体功法"
			CultivationTechnique.TechniqueType.MOVEMENT:
				type_text += "身法功法"
			CultivationTechnique.TechniqueType.ADVANCED:
				type_text += "高级功法"
		if current_type_label:
			current_type_label.text = type_text
		
		# 更新元素亲和
		var element_text = "元素亲和: "
		if current_technique.element_affinity == "none":
			element_text += "无"
		else:
			element_text += current_technique.element_affinity.capitalize()
		if current_element_label:
			current_element_label.text = element_text
		
		# 更新修炼加成
		if current_cultivation_speed_label:
			current_cultivation_speed_label.text = "修炼速度加成: x%.1f" % current_technique.cultivation_speed_bonus
		if current_spirit_recovery_label:
			current_spirit_recovery_label.text = "真气恢复加成: x%.1f" % current_technique.spirit_recovery_bonus
		if current_breakthrough_label:
			current_breakthrough_label.text = "突破几率加成: x%.1f" % current_technique.breakthrough_bonus
		
		# 更新属性加成
		if current_attack_label:
			current_attack_label.text = "攻击: +%d" % current_technique.attack_bonus
		if current_defense_label:
			current_defense_label.text = "防御: +%d" % current_technique.defense_bonus
		if current_speed_label:
			current_speed_label.text = "速度: +%d" % current_technique.speed_bonus
		
		# 更新修炼按钮状态
		if cultivate_button:
			if current_technique.level >= current_technique.max_level:
				cultivate_button.text = "已达最高等级"
				cultivate_button.disabled = true
			else:
				cultivate_button.text = "修炼"
				cultivate_button.disabled = false
	else:
		# 没有功法时显示默认信息
		if current_name_label:
			current_name_label.text = "未选择功法"
		if current_level_label:
			current_level_label.text = "等级: 0/0"
		if current_progress_bar:
			current_progress_bar.value = 0
		if current_description_label:
			current_description_label.text = "请选择一门功法开始修炼。"
		if current_type_label:
			current_type_label.text = "类型: 无"
		if current_element_label:
			current_element_label.text = "元素亲和: 无"
		if current_cultivation_speed_label:
			current_cultivation_speed_label.text = "修炼速度加成: x0.0"
		if current_spirit_recovery_label:
			current_spirit_recovery_label.text = "真气恢复加成: x0.0"
		if current_breakthrough_label:
			current_breakthrough_label.text = "突破几率加成: x0.0"
		if current_attack_label:
			current_attack_label.text = "攻击: +0"
		if current_defense_label:
			current_defense_label.text = "防御: +0"
		if current_speed_label:
			current_speed_label.text = "速度: +0"
		if cultivate_button:
			cultivate_button.text = "选择功法"
			cultivate_button.disabled = true

# 填充功法列表
func populate_technique_list() -> void:
	# 检查节点引用和数据管理器
	if not technique_container or not data_manager or not player:
		return
	
	# 获取所有功法数据
	var techniques_data = data_manager.techniques_data
	if not techniques_data:
		return
	
	# 遍历功法数据
	for technique_id in techniques_data:
		var technique_data = techniques_data[technique_id]
		
		# 创建功法按钮
		var technique_button = Button.new()
		technique_button.text = technique_data.name
		technique_button.custom_minimum_size = Vector2(0, 40)
		technique_button.size_flags_horizontal = Control.SIZE_EXPAND_FILL
		
		# 检查是否可以修炼该功法
		var can_cultivate = true
		if technique_data.required_realm > player.cultivation_realm:
			can_cultivate = false
			technique_button.text += " (境界不足)"
			technique_button.disabled = true
		
		# 检查灵根要求
		if technique_data.required_spirit_root != "any":
			var has_required_root = false
			for root in player.spirit_roots:
				if str(root) == technique_data.required_spirit_root:
					has_required_root = true
					break
			
			if not has_required_root:
				can_cultivate = false
				technique_button.text += " (灵根不符)"
				technique_button.disabled = true
		
		# 如果是当前功法，标记出来
		if current_technique and current_technique.technique_name == technique_data.name:
			technique_button.text += " (当前)"
			technique_button.disabled = true
		
		# 连接按钮信号
		technique_button.pressed.connect(_on_technique_button_pressed.bind(technique_id))
		
		# 添加到容器
		technique_container.add_child(technique_button)

# 更新突破按钮状态
func update_breakthrough_button() -> void:
	if not breakthrough_button:
		return
		
	if current_technique and current_technique.level >= current_technique.max_level:
		breakthrough_button.disabled = false
	else:
		breakthrough_button.disabled = true

# 功法按钮点击事件
func _on_technique_button_pressed(technique_id: String) -> void:
	# 创建功法实例
	var technique = data_manager.create_technique(technique_id)
	
	# 设置为当前功法
	player.set_cultivation_technique(technique)
	
	# 更新当前功法
	current_technique = technique
	
	# 更新界面
	update_ui()

# 修炼按钮点击事件
func _on_cultivate_button_pressed() -> void:
	if current_technique:
		# 检查灵石是否足够
		var required_stones = 10  # 每次修炼消耗的灵石数量
		if player.spirit_stones < required_stones:
			push_error("灵石不足，无法修炼！")
			return
		
		# 开始修炼
		if cultivation_system.start_cultivation(10.0, required_stones):
			# 扣除灵石
			player.spirit_stones -= required_stones
			
			# 这里可以添加修炼动画或效果
			
			# 更新界面
			update_ui()

# 突破按钮点击事件
func _on_breakthrough_button_pressed() -> void:
	if current_technique and current_technique.level >= current_technique.max_level:
		# 尝试突破
		var success = cultivation_system._check_breakthrough()
		
		# 根据突破结果显示不同信息
		if success:
			# 突破成功，可以显示一个成功的提示
			print("突破成功！")
		else:
			# 突破失败，可以显示一个失败的提示
			print("突破失败！")
		
		# 更新界面
		update_ui()

# 关闭按钮点击事件
func _on_close_button_pressed() -> void:
	hide_ui()
